package api

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
	"net/http"
	"net/url"
	"project_api/user_web/forms"
	"project_api/user_web/utils"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"project_api/user_web/global"
)

// SendSmsAli 阿里云发送短信验证码
func SendSmsAli(ctx *gin.Context) {
	sendSmsForm := forms.SendSmsForm{}
	if err := ctx.ShouldBind(&sendSmsForm); err != nil {
		HandleValidatorError(ctx, err)
		return
	}

	client, err := dysmsapi.NewClientWithAccessKey("cn-beijing", global.ServerConfig.AliSmsInfo.ApiKey, global.ServerConfig.AliSmsInfo.ApiSecrect)
	if err != nil {
		panic(err)
	}
	smsCode := utils.GenerateSmsCode(4)
	request := requests.NewCommonRequest()
	request.Method = "POST"
	request.Scheme = "https" // https | http
	request.Domain = "dysmsapi.aliyuncs.com"
	request.Version = "2017-05-25"
	request.ApiName = "SendSms"
	request.QueryParams["RegionId"] = "cn-beijing"
	request.QueryParams["PhoneNumbers"] = sendSmsForm.Mobile            //手机号
	request.QueryParams["SignName"] = "慕学在线"                            //阿里云验证过的项目名 自己设置
	request.QueryParams["TemplateCode"] = "SMS_181850725"               //阿里云的短信模板号 自己设置
	request.QueryParams["TemplateParam"] = "{\"code\":" + smsCode + "}" //短信模板中的验证码内容 自己生成   之前试过直接返回，但是失败，加上code成功。
	response, err := client.ProcessCommonRequest(request)
	fmt.Print(client.DoAction(request, response))
	if err != nil {
		fmt.Print(err.Error())
	}
	//将验证码保存起来 - redis
	rdb := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", global.ServerConfig.RedisInfo.Host, global.ServerConfig.RedisInfo.Port),
	})
	rdb.Set(context.Background(), sendSmsForm.Mobile, smsCode, time.Duration(global.ServerConfig.RedisInfo.Expire)*time.Second)

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "发送成功",
	})
}

// SmsPartResponse  响应结构体
type SmsPartResponse struct {
	ErrorCode int    `json:"error_code"`
	Reason    string `json:"reason"`
	Result    string `json:"result"`
	Sn        string `json:"sn"`
}

func SendSmsPart(ctx *gin.Context) {
	sendSmsForm := forms.SendSmsForm{}
	if err := ctx.ShouldBind(&sendSmsForm); err != nil {
		HandleValidatorError(ctx, err)
		return
	}

	// 参数
	host := "https://smsv2.market.alicloudapi.com"
	path := "/sms/sendv2"
	appCode := global.ServerConfig.AliSmsPartInfo.Appcode // 请替换为实际的AppCode
	code := utils.GenerateSmsCode(4)                      // 假设验证码

	// 消息内容
	content := "【时光语音】您的验证码是%s。如非本人操作，请忽略本短信"
	content = fmt.Sprintf(content, code)

	// 编码消息内容
	msgContent := url.QueryEscape(content)

	// 构建查询参数
	queryParams := fmt.Sprintf("mobile=%s&content=%s", sendSmsForm.Mobile, msgContent)

	// 拼接完整URL
	urlStr := host + path + "?" + queryParams

	// 创建 resty 客户端
	client := resty.New()

	// 发送 GET 请求
	resp, err := client.R().
		SetHeader("Authorization", "APPCODE "+appCode). // 设置请求头
		Get(urlStr)                                     // 发送 GET 请求

	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}

	if resp.IsError() {
		fmt.Println("Error sending request:", resp.Status())
	}

	var apiResponse SmsPartResponse
	body := resp.Body()
	if err := json.Unmarshal(body, &apiResponse); err != nil {
		fmt.Println("Error parsing response body:", err)
		return
	}

	if apiResponse.ErrorCode != 0 {
		fmt.Println("Error sending request:", apiResponse.Reason)
		return
	}
	//将验证码保存起来 - redis
	rdb := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", global.ServerConfig.RedisInfo.Host, global.ServerConfig.RedisInfo.Port),
	})
	rdb.Set(context.Background(), sendSmsForm.Mobile, code, time.Duration(global.ServerConfig.RedisInfo.Expire)*time.Second)

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "发送成功",
	})
}
